package cloud.alibaba.study.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

public class BaseService {

	@Autowired
	private TransactionTemplate transactionTemplate;
	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;

	public TransactionTemplate getTransactionTemplate() {
		return transactionTemplate;
	}

	protected Object execute(TransactionService tr) throws Exception {
		return execute(tr, true);
	}

	protected Object execute(final TransactionService tr, boolean doExceptFlag) throws Exception {
		final Object obj = getTransactionTemplate().execute(new TransactionCallback<Object>() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				try {
					return tr.doTransaction();
				} catch (Exception e) {
					status.setRollbackOnly();
					return new Exception("系统发生异常，异常信息：" + e.getMessage());
				}
			}
		});
		if (obj instanceof Exception) {
			Exception ex = (Exception) obj;
			throw ex;
		} else {
			if (doExceptFlag) {
				try {
					taskExecutor.execute(new Runnable() {
						@Override
						public void run() {
							tr.doExceptTransaction(obj);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("execute方法的事物外执行程序出错，错误信息：" + e.getMessage());
				}
			}
		}
		return obj;
	}

	public interface TransactionService {
		/**
		 * 实现正常事物业务逻辑
		 * 
		 * @Author 赵航
		 * @Date 2016年10月27日
		 * @return 根据自己的实际需要，返回值，该值将作为doExceptTransaction方法的参数
		 * @throws Exception
		 */
		Object doTransaction() throws Exception;

		/**
		 * 实现正常事物之外的业务逻辑（比如发送短信，微信推送，向消息队列中打消息等等）
		 * 
		 * @Author 赵航
		 * @Date 2016年10月27日
		 * @param obj
		 */
		void doExceptTransaction(Object obj);
	}
}
